package com.example.iread.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.room.Room;

import com.example.iread.database.IReadDb;
import com.example.iread.exception.MyCatchException;
import com.example.iread.util.FloatWindowUtil;
import com.facebook.stetho.Stetho;

import java.lang.ref.WeakReference;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MyApplication extends Application {

    private static MyApplication app;

//    public final String baseUrl = "http://192.168.1.103:3007";

    /**
     * 核心线程数
     * 最大线程数
     * 超时时间
     * 时间单位
     * 任务队列
     */
    public final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 2, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(128));
    private IReadDb iReadDb;

    public static MyApplication getInstance() {
        return app;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        Stetho.initializeWithDefaults(this);
        createDatabase();
        setting();
        MyCatchException.getInstance().init();
        activityLifecycleListener();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void createDatabase() {
        iReadDb = Room.databaseBuilder(this, IReadDb.class, "i_read")
                .addMigrations()
                .allowMainThreadQueries()
                .build();
    }

    public IReadDb getDb() {
        return iReadDb;
    }

    private void setting() {
        SharedPreferences setting = getSharedPreferences("setting", Context.MODE_PRIVATE);
        boolean nightMode = setting.getBoolean("night_mode", false);
        AppCompatDelegate.setDefaultNightMode(nightMode ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
    }

    public void activityLifecycleListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            private WeakReference<Activity> weakCurrentActivity;
            private WeakReference<ViewTreeObserver.OnGlobalLayoutListener> weakGlobalListener;
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {}

            @Override
            public void onActivityStarted(@NonNull Activity activity) {}

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

                weakCurrentActivity = new WeakReference<>(activity);
                View decorView = activity.getWindow().getDecorView();
                ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();

                if (decorView.getWindowToken() != null) {
                    FloatWindowUtil.getInstance().updateToken(activity);
                } else {
                    ViewTreeObserver.OnGlobalLayoutListener globalListener  = new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            if (activity.getWindow() != null) {
                                FloatWindowUtil.getInstance().updateToken(activity);
                            }

                            if (decorView.getViewTreeObserver() != null) {
                                decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            }
                        }
                    };

                    viewTreeObserver.addOnGlobalLayoutListener(globalListener);
                    weakGlobalListener = new WeakReference<>(globalListener);
                }
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                // FloatWindowUtils.unbindDebugPanelFloatWindow(activity);
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }
}
